using System;
using System.Collections.Generic;
using System.Linq;
using MimeCloud.Foundations.Extensions;

namespace MimeCloud.Foundations.Repositories
{
    public class InMemoryDataContext : IDataContext
    {
        private readonly List<object> _inMemoryDataStore = new List<object>();

        /// <summary>
        /// Gets the repository for the given type of entities
        /// </summary>
        /// <typeparam name="T">The type of the entity</typeparam>
        /// <returns>The repository of the given type</returns>
        public IQueryable<T> Repository<T>() where T : class
        {
            var query = from objects in _inMemoryDataStore
                        where typeof (T).IsAssignableFrom(objects.GetType())
                        select objects;

            return query.Select(o => (T) o).AsQueryable();
        }

        /// <summary>
        /// Adds a new entity to the repository
        /// </summary>
        /// <typeparam name="T">The type of the entity</typeparam>
        /// <param name="item">The entity to add</param>
        public void Insert<T>(T item) where T : class
        {
            _inMemoryDataStore.Add(item);
        }

        /// <summary>
        /// Deletes the specified entity from the repository
        /// </summary>
        /// <typeparam name="T">The type of the entity</typeparam>
        /// <param name="item">The entity to delete</param>
        public void Delete<T>(T item) where T : class
        {
           _inMemoryDataStore.Remove(item);
        }

        /// <summary>
        /// Commits the changes to the repository
        /// </summary>
        public void Commit()
        {
            OnCommitExecuted(EventArgs.Empty);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            
        }

        /// <summary>
        /// Invokes the completed.
        /// </summary>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void OnCommitExecuted(EventArgs e)
        {
            EventHandler handler = CommitExecuted;
            
            if (handler != null) 
                handler(this, e);
        }

        #region IDataContext Members

        public event EventHandler CommitExecuted;

        #endregion

        #region IDataContext Members


        /// <summary>
        /// Deletes the specified entity from the repository
        /// </summary>
        /// <typeparam name="T">The type of the entity</typeparam>
        public void DeleteAll<T>() where T : class
        {
            _inMemoryDataStore.Clear();
        }

        #endregion
    }
}